import { ElMessage } from "element-plus";

const inMenus = (path) => {
  let menus = Storage.get("menus", true);
  const f = (arr) => {
    let flag = false;
    arr?.some((v) => {
      if (v.path === path) {
        flag = true;
      } else if (v.children?.length) {
        let _flag = f(v.children);
        if (_flag) {
          flag = true;
        }
      }
    });
    return flag;
  };
  return f(menus);
};

export function redirectUrl(router) {
  router.beforeEach(async (to, from, next) => {
    let path = to.path
    if(to.meta.parent){
      path = to.meta.parent
    }
    if (path === "/login" || path === "/redirect") {
      next();
      return;
    }
    // 本地获取用户登录信息
    let userInfo = Storage.get("user", true);
    let token = Storage.get("token", true);
    let menus = Storage.get("menus", true);
    let loginPage = Storage.get("loginPage", true);
    const _inMenus = inMenus(path);

    if ((!userInfo || !token || !menus) && path !== "/login") {
      next({
        path: "/" + (loginPage || "login"),
      });
    } else if (!_inMenus) {
      return;
    } else {
      next();
    }
  });
}
